/**
 * Copyright (C) 2008 Happy Fish / YuQing
 * <p>
 * FastDFS Java Client may be copied only under the terms of the GNU Lesser
 * General Public License (LGPL).
 * Please visit the FastDFS Home Page http://www.csource.org/ for more detail.
 */

package cc.siyecao.fastdfs.downloader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * DowloadCallback test
 *
 * @author Happy Fish / YuQing
 * @version Version 1.3
 */
public class FileWriterDownloader implements Downloader {
    private File file;
    private FileOutputStream out = null;
    private long currentBytes = 0;

    public FileWriterDownloader(File file) {
        this.file = file;
    }

    @Override
    public int download(long fileSize, byte[] buff, int data) {
        try {
            if (this.out == null) {
                this.out = new FileOutputStream( this.file );
            }

            this.out.write( buff, 0, data );
            this.currentBytes += data;

            if (this.currentBytes == fileSize) {
                this.out.close();
                this.out = null;
                this.currentBytes = 0;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            return -1;
        } finally {
            if (this.out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return 0;
    }

    @Override
    protected void finalize() throws Throwable {
        if (this.out != null) {
            this.out.close();
            this.out = null;
        }
    }
}
